from flask import Flask, render_template, request, redirect, url_for, jsonify, flash
import requests

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# 智谱AI评分API的配置
API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
API_KEY = "60c0a3a620d58380b59ca64d0ed94b86.EyYLCpgcHx2BJ75U"  # 替换为你的API密钥

# 自动评分函数
def score_answer(student_answer, correct_answer):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "messages": [
            {"role": "system", "content": "请对以下学生答案进行评分并提供反馈："},
            {"role": "user", "content": f"学生答案：{student_answer}\n正确答案：{correct_answer}"}
        ]
    }
    response = requests.post(API_URL, headers=headers, json=payload)

    if response.status_code == 200:
        result = response.json()
        # 处理返回的评分结果
        score = result['choices'][0]['message']['content'].strip()
        return score
    else:
        return "评分失败"

# 首页（输入答案页面）
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        student_answer = request.form['student_answer']
        correct_answer = request.form['correct_answer']
        return redirect(url_for('result', student_answer=student_answer, correct_answer=correct_answer))
    return render_template('index.html')

# 显示评分结果的页面
@app.route('/result')
def result():
    student_answer = request.args.get('student_answer')
    correct_answer = request.args.get('correct_answer')
    score = score_answer(student_answer, correct_answer)
    return render_template('result.html', score=score)
def score_answer(student_answer, correct_answer):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "GLM-4",
        "messages": [
            {"role": "system", "content": "请对以下学生答案进行评分并提供反馈："},
            {"role": "user", "content": f"学生答案：{student_answer}\n正确答案：{correct_answer}"}
        ]
    }
    response = requests.post(API_URL, headers=headers, json=payload)

    # 调试信息，打印返回的完整内容
    print(response.text)

    if response.status_code == 200:
        result = response.json()
        score = result['choices'][0]['message']['content'].strip()
        return score
    else:
        return "评分失败"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
